package cn.wolfcode.trip.admin;

import cn.wolfcode.trip.core.domain.Region;
import cn.wolfcode.trip.core.query.QueryObject;
import cn.wolfcode.trip.core.service.IRegionService;
import cn.wolfcode.trip.core.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("region")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @RequestMapping("list")
    public String list(@ModelAttribute("qo") QueryObject qo,Model model){

        return "region/list";
    }

    // 返回treeview需要的数据
    @RequestMapping(value = "selectByParent",params = "type=tree")
    @ResponseBody
    public List<Map> selectByParent(Long parentId) {

        List<Region> list = regionService.queryByParent(parentId);
        //用于存储需要返回的数据
        ArrayList<Map> data = new ArrayList<>();

        for (Region region : list) {//转换为treeview插件需要的格式
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",region.getId());
            map.put("text",region.getName());
            if(region.getState()==Region.STATE_HOT) {
                map.put("tags", new String[]{"推荐"});
            }
            map.put("lazyLoad",true);
            data.add(map);
        }

        return data;
    }

    // 返回table需要的数据
    @RequestMapping(value = "selectByParent",params = "type=table")
    @ResponseBody
    public List<Region> selectByParentForTable(Long parentId){

        List<Region> list = regionService.queryByParent(parentId);
        return list;
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Region region){

        JsonResult json = new JsonResult();
        try {
            regionService.saveOrUpdate(region);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    @RequestMapping("updateState")
    @ResponseBody
    public JsonResult updateState(Long id,Integer state){

        JsonResult json = new JsonResult();
        try {
            regionService.updateState(id,state);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }
}
